package com.okcl.manager.Interceptor;

import com.alibaba.fastjson2.JSON;
import com.okcl.manager.constant.RedisKeyConstants;
import com.okcl.model.entity.system.SysUser;
import com.okcl.model.vo.common.Result;
import com.okcl.model.vo.common.ResultCodeEnum;
import com.okcl.utils.AuthContextUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class LoginAuthInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token) || token.isEmpty()) {
            responseNoLoginInfo(response);
            return false;
        }
        String userInfoStr = stringRedisTemplate.opsForValue().get(RedisKeyConstants.LOGIN_KEY + token);
        if (!StringUtils.hasText(userInfoStr)) {
            responseNoLoginInfo(response);
            return false;
        }
        //存入到当前线程中
        AuthContextUtil.setUser(JSON.parseObject(userInfoStr, SysUser.class));
        //刷新redis中的用户过期时间
        stringRedisTemplate.expire(RedisKeyConstants.LOGIN_KEY + token, RedisKeyConstants.LOGIN_EXPIRE_TIME, TimeUnit.MINUTES);
        log.info("刷新token");
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    //响应208状态码给前端
    private void responseNoLoginInfo(HttpServletResponse response) {
        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) writer.close();
        }
    }
}
